<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <input type="file" id="input">
  <button id="upload">上传</button>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <script>
    const input = document.getElementById('input')
    const upload = document.getElementById('upload')
    upload.addEventListener('click', handleUpload)
    input.addEventListener('change', handleChange)

    let fileObj = null

    function handleChange(e) {
      console.log(e.target.files)
      const [file] = e.target.files
      fileObj = file
    }
  
    function handleUpload() {
      if (!fileObj) {
        return
      }
      // 将 fileObj 切片
      const chunkList = createChunk(fileObj)
      // console.log(chunkList);
      // 给切片打上编号
      const chunks = chunkList.map(({file}, index) => {
        return {
          file,
          size: file.size,
          chunkName: `${fileObj.name}-${index}`,
          fileName: fileObj.name,
          index
        }
      })
      // console.log(chunks)
      // 上传切片
      uploadChunks(chunks)
    }
  
    function createChunk(file, size = 5 * 1024 * 1024) {
      const chunkList = []
      let cur = 0
      while (cur < file.size) {
        chunkList.push({
          file: file.slice(cur, cur + size)
        })
        cur += size
      }
      return chunkList
    }
  
    function uploadChunks(chunks) { // 向后端传输切片
      // 将切片处理成 FormData 格式
      const formChunks = chunks.map(({file, fileName, index, chunkName}) => {
        const formData = new FormData()
        formData.append('file', file)
        formData.append('fileName', fileName)
        formData.append('chunkName', chunkName)
        return {formData, index}
      })

      // console.log(formChunks);
      // 发请求
      const requestList = formChunks.map(({formData, index}) => {
        return axios.post('http://localhost:3000/upload', formData)
      })

      Promise.all(requestList).then(res => {
        console.log(res)
      })

    }
  </script>
</body>
</html>